from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.contrib.auth.models import User
from django.utils import timezone
from .models import Ticket, MaintenanceRecord, TicketImage
from .forms import TicketCreateForm, MaintenanceRecordForm, TicketRegisterForm
from assets.models import Asset

@login_required
def ticket_create(request):
    """创建工单 - 支持图片上传的原子操作"""
    if request.method == 'POST':
        # 调试信息：检查接收到的文件
        print(f"Request FILES: {dict(request.FILES)}")
        print(f"Request POST: {dict(request.POST)}")
        
        form = TicketCreateForm(request.POST, request.FILES, user=request.user)
        
        if form.is_valid():
            try:
                # 创建工单实例
                ticket = form.save(commit=False)
                ticket.created_by = request.user
                
                # 根据提交类型设置状态
                if 'save_draft' in request.POST:  # 保存草稿
                    ticket.status = 'draft'
                    success_msg = '工单草稿保存成功！'
                elif 'submit' in request.POST:    # 正式提交
                    ticket.status = 'applied'
                    success_msg = '维修申请提交成功！'
                else:
                    ticket.status = 'draft'
                    success_msg = '工单保存成功！'
                
                # 原子性保存（包括工单、设备关联、图片）
                ticket = form.save(commit=True)
                
                # 记录成功信息
                image_count = len(request.FILES.getlist('images')) if request.FILES else 0
                if image_count > 0:
                    messages.success(request, f'{success_msg} 已上传 {image_count} 张图片。')
                else:
                    messages.success(request, success_msg)
                    
                return redirect('tickets:ticket_list_mine')
                    
            except Exception as e:
                messages.error(request, f'保存失败：{str(e)}')
                print(f"保存错误: {str(e)}")
        else:
            # 表单验证失败
            messages.error(request, '请检查输入信息是否正确')
            print(f"表单验证错误: {form.errors}")
    
    else:
        form = TicketCreateForm(user=request.user)
    
    return render(request, 'tickets/create.html', {'form': form})

@login_required
def ticket_list_mine(request):
    """我的工单列表（客户查看自己的工单）"""
    tickets = Ticket.objects.filter(created_by=request.user).order_by('-created_at')
    return render(request, 'tickets/list_mine.html', {'tickets': tickets})

@login_required
def ticket_edit(request, pk):
    """编辑工单（主要用于编辑草稿）"""
    ticket = get_object_or_404(Ticket, pk=pk)
    
    # 权限检查：只有创建者可以编辑自己的草稿
    if request.user != ticket.created_by:
        messages.error(request, '您没有权限编辑此工单')
        return redirect('tickets:ticket_list_mine')
    
    # 状态检查：只能编辑草稿状态的工单
    if ticket.status != 'draft':
        messages.error(request, '只能编辑草稿状态的工单')
        return redirect('tickets:ticket_detail', pk=pk)
    
    if request.method == 'POST':
        form = TicketCreateForm(request.POST, request.FILES, instance=ticket, user=request.user)
        if form.is_valid():
            try:
                updated_ticket = form.save(commit=False)
                
                # 根据按钮类型设置不同状态
                if 'save_draft' in request.POST:  # 保存草稿
                    updated_ticket.status = 'draft'  # 保持草稿状态
                    success_msg = '工单草稿更新成功！'
                elif 'submit' in request.POST:    # 正式提交
                    updated_ticket.status = 'applied'  # 更新为维修申请状态
                    success_msg = '工单提交成功！'
                else:
                    updated_ticket.status = 'draft'
                    success_msg = '工单更新成功！'
                
                # 保存工单（包括图片处理）
                form.save()
                
                # 记录成功信息
                image_count = len(request.FILES.getlist('images')) if request.FILES else 0
                delete_count = len(form.cleaned_data.get('delete_images', [])) if hasattr(form, 'cleaned_data') else 0
                
                # 调试信息：检查保存后的图片数量
                updated_ticket = Ticket.objects.get(pk=ticket.pk)
                final_image_count = updated_ticket.images.count()
                print(f"After save - Original images: {ticket.images.count()}, Final images: {final_image_count}")
                
                if image_count > 0 or delete_count > 0:
                    messages.success(request, f'{success_msg} 已{"添加" if image_count > 0 else ""}{"和" if image_count > 0 and delete_count > 0 else ""}{"删除" if delete_count > 0 else ""}图片。')
                else:
                    messages.success(request, success_msg)
                    
                return redirect('tickets:ticket_list_mine')
                    
            except Exception as e:
                messages.error(request, f'保存失败：{str(e)}')
                print(f"保存错误: {str(e)}")
        else:
            # 表单验证失败
            messages.error(request, '请检查输入信息是否正确')
            print(f"表单验证错误: {form.errors}")
    else:
        form = TicketCreateForm(instance=ticket, user=request.user)
    
    return render(request, 'tickets/edit.html', {
        'form': form,
        'ticket': ticket
    })

@login_required
def ticket_detail(request, pk):
    """工单详情"""
    ticket = get_object_or_404(Ticket, pk=pk)
    
    # 权限检查：创建者、分配的技术人员、管理员、前台或质检员可以查看
    if not (request.user == ticket.created_by or 
            request.user == ticket.assigned_to or 
            request.user.is_staff or
            (hasattr(request.user, 'profile') and 
             (request.user.profile.role == 'receptionist' or 
              request.user.profile.role == 'quality_checker'))):
            messages.error(request, '您没有权限查看此工单')
            return redirect('dashboard')
    
    # 预加载维修记录及其关联的备件使用记录
    maintenance_records = MaintenanceRecord.objects.filter(ticket=ticket).prefetch_related('spare_part_usage__spare_part')
    # 获取工单的所有图片，按order字段排序
    ticket_images = TicketImage.objects.filter(ticket=ticket).order_by('order')
    
    # 将图片分为两类：创建时上传的图片和接收时上传的图片
    creation_images = []
    registration_images = []
    
    for image in ticket_images:
        if image.description and '登记签收图片' in image.description:
            registration_images.append(image)
        else:
            creation_images.append(image)
    
    return render(request, 'tickets/detail.html', {
        'ticket': ticket,
        'maintenance_records': maintenance_records,
        'ticket_images': ticket_images,
        'creation_images': creation_images,
        'registration_images': registration_images
    })

@login_required
def ticket_list_assigned(request):
    """技术人员查看分配的工单"""
    if not hasattr(request.user, 'profile') or request.user.profile.role != 'technician':
            messages.error(request, '您不是技术人员，无法查看分配工单')
            return redirect('dashboard')
    
    # 技术人员可以看到分配给自己的所有工单（包括设备分配、检测、维修状态）
    tickets = Ticket.objects.filter(assigned_to=request.user).order_by('-created_at')
    return render(request, 'tickets/list_assigned.html', {'tickets': tickets})

@login_required
def ticket_process(request, pk):
    """技术人员处理工单"""
    ticket = get_object_or_404(Ticket, pk=pk)
    
    # 权限检查：根据工单状态和用户角色进行精细控制
    if ticket.status in ['testing', 'repairing', 'quality_check']:
        # 检测、维修、质检环节：管理员可以在所有环节操作
        if request.user.is_staff:
            pass  # 管理员有权限
        elif ticket.status in ['testing', 'repairing']:
            # 检测和维修环节：分配的技术人员可以操作
            if request.user != ticket.assigned_to:
                messages.error(request, '您没有权限处理此工单')
                return redirect('tickets:ticket_list_assigned')
        elif ticket.status == 'quality_check':
            # 质检环节：质检员可以操作
            if not (hasattr(request.user, 'profile') and request.user.profile.role == 'quality_checker'):
                messages.error(request, '您没有权限处理此工单')
                return redirect('tickets:ticket_list_assigned')
    else:
        # 其他状态不允许处理操作
        messages.error(request, '当前状态下不允许此操作')
        return redirect('tickets:ticket_detail', pk=pk)
    
    if request.method == 'POST':
        # 处理工单状态更新
        action = request.POST.get('action')
        if action == 'testing':
            ticket.status = 'testing'
            ticket.testing_at = timezone.now()
            ticket.save()
            messages.success(request, '已开始检测')
        elif action == 'repairing':
            ticket.status = 'repairing'
            ticket.repairing_at = timezone.now()
            ticket.save()
            messages.success(request, '已开始维修')
        elif action == 'quality_check':
            ticket.status = 'quality_check'
            ticket.quality_check_at = timezone.now()
            ticket.save()
            messages.success(request, '已开始质检')
        elif action == 'completed':
            ticket.status = 'completed'
            ticket.completed_at = timezone.now()
            ticket.save()
            messages.success(request, '维修已完成')
        elif action == 'returned':
            ticket.status = 'returned'
            ticket.returned_at = timezone.now()
            ticket.save()
            messages.success(request, '设备已返还客户')
        elif action == 'scrap':
            # 报废操作：更新所有关联设备状态为报废
            for asset in ticket.assets.all():
                asset.status = 'retired'
                asset.save()
            
            # 更新工单状态为终止
            ticket.status = 'terminated'
            ticket.save()
            messages.success(request, '设备已报废，工单已终止')
        
        return redirect('tickets:ticket_detail', pk=pk)
    
    maintenance_records = MaintenanceRecord.objects.filter(ticket=ticket)
    return render(request, 'tickets/process.html', {
        'ticket': ticket,
        'maintenance_records': maintenance_records
    })

@login_required
def add_maintenance_record(request, pk):
    """添加维修记录"""
    ticket = get_object_or_404(Ticket, pk=pk)
    
    # 权限检查：只有分配的技术人员或管理员可以添加记录
    if request.user != ticket.assigned_to and not request.user.is_staff:
        messages.error(request, '您没有权限添加维修记录')
        return redirect('tickets:ticket_detail', pk=pk)
    
    if request.method == 'POST':
        form = MaintenanceRecordForm(request.POST)
        if form.is_valid():
            try:
                record = form.save(commit=False)
                record.ticket = ticket
                record.technician = request.user
                
                # 保存维修记录（包括备件使用处理）
                record = form.save()
                
                messages.success(request, '维修记录添加成功')
                return redirect('tickets:ticket_detail', pk=pk)
                
            except Exception as e:
                messages.error(request, f'保存失败：{str(e)}')
                print(f"维修记录保存错误: {str(e)}")
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f'{field}: {error}')
    else:
        form = MaintenanceRecordForm()
    
    # 获取现有的维修记录
    maintenance_records = MaintenanceRecord.objects.filter(ticket=ticket).order_by('-created_at')
    
    return render(request, 'tickets/add_record.html', {
        'form': form,
        'ticket': ticket,
        'maintenance_records': maintenance_records
    })

@login_required
def ticket_list_all(request):
    """查看所有工单（管理员和前台）"""
    # 权限检查：管理员或前台可以查看所有工单
    if not (request.user.is_staff or 
            (hasattr(request.user, 'profile') and request.user.profile.role == 'receptionist')):
        messages.error(request, '您没有权限查看所有工单')
        return redirect('dashboard')
    
    tickets = Ticket.objects.all().order_by('-created_at')
    
    # 根据用户角色返回不同的模板
    if hasattr(request.user, 'profile') and request.user.profile.role == 'receptionist':
        return render(request, 'tickets/list_receptionist.html', {'tickets': tickets})
    else:
        return render(request, 'tickets/list_all.html', {'tickets': tickets})

@login_required
def ticket_assign(request, pk):
    """管理员分配工单给技术人员"""
    if not request.user.is_staff:
        messages.error(request, '您不是管理员，无法分配工单')
        return redirect('dashboard')
    
    ticket = get_object_or_404(Ticket, pk=pk)
    
    # 状态检查：只能在登记签收中状态下操作
    if ticket.status != 'registered':
        messages.error(request, '只能在登记签收中状态下操作')
        return redirect('tickets:ticket_detail', pk=pk)
    
    if request.method == 'POST':
        technician_id = request.POST.get('technician')
        if technician_id:
            try:
                technician = User.objects.get(id=technician_id)
                # 检查用户是否是技术人员
                if hasattr(technician, 'profile') and technician.profile.role == 'technician':
                    ticket.assigned_to = technician
                    ticket.assigned_by = request.user
                    ticket.assigned_at = timezone.now()
                    ticket.status = 'assigned'  # 更新状态为设备分配中
                    ticket.save()
                    messages.success(request, f'工单已成功分配给 {technician.username}，状态已更新为设备分配中')
                    return redirect('tickets:ticket_list_all')
                else:
                    messages.error(request, '只能分配给技术人员')
            except User.DoesNotExist:
                messages.error(request, '用户不存在')
    
    # 获取所有技术人员
    technicians = User.objects.filter(profile__role='technician')
    return render(request, 'tickets/assign.html', {
        'ticket': ticket,
        'technicians': technicians
    })

@login_required
def ticket_register(request, pk):
    """登记签收工单 - 允许前台添加设备信息"""
    # 权限检查：管理员或前台可以登记签收
    if not (request.user.is_staff or 
            (hasattr(request.user, 'profile') and request.user.profile.role == 'receptionist')):
        messages.error(request, '您没有权限登记签收')
        return redirect('dashboard')
    
    ticket = get_object_or_404(Ticket, pk=pk)
    
    # 状态检查：只能在维修申请状态下操作
    if ticket.status != 'applied':
        messages.error(request, '只能在维修申请状态下操作')
        return redirect('tickets:ticket_detail', pk=pk)
    
    if request.method == 'POST':
        form = TicketRegisterForm(request.POST, request.FILES, ticket=ticket)
        if form.is_valid():
            try:
                # 更新工单状态和信息
                ticket.status = 'registered'
                ticket.registered_at = timezone.now()
                ticket.registered_by = request.user
                ticket.save()
                
                # 使用表单的save方法处理设备和图片
                form.instance = ticket  # 设置表单实例为当前工单
                form.save()
                
                # 记录成功信息
                image_count = len(request.FILES.getlist('images')) if request.FILES else 0
                if image_count > 0:
                    messages.success(request, f'工单已登记签收，状态已更新为登记签收中，已上传 {image_count} 张图片。')
                else:
                    messages.success(request, '工单已登记签收，状态已更新为登记签收中')
                    
                return redirect('tickets:ticket_detail', pk=pk)
                    
            except Exception as e:
                messages.error(request, f'登记签收失败：{str(e)}')
                print(f"登记签收错误: {str(e)}")
    else:
        form = TicketRegisterForm(ticket=ticket)
    
    return render(request, 'tickets/register.html', {
        'form': form,
        'ticket': ticket
    })

@login_required
def ticket_testing(request, pk):
    """开始检测"""
    ticket = get_object_or_404(Ticket, pk=pk)
    # 权限检查：只有分配的技术人员或管理员可以进行检测
    if request.user != ticket.assigned_to and not request.user.is_staff:
        messages.error(request, '您没有权限进行检测')
        return redirect('tickets:ticket_detail', pk=pk)
    
    # 状态检查：只能在设备分配中状态下操作
    if ticket.status != 'assigned':
        messages.error(request, '只能在设备分配中状态下操作')
        return redirect('tickets:ticket_detail', pk=pk)
    
    ticket.status = 'testing'
    ticket.testing_at = timezone.now()
    ticket.save()
    messages.success(request, '已开始检测，状态已更新为设备检测中')
    return redirect('tickets:ticket_detail', pk=pk)

@login_required
def ticket_repairing(request, pk):
    """开始维修"""
    ticket = get_object_or_404(Ticket, pk=pk)
    # 权限检查：只有分配的技术人员或管理员可以进行维修
    if request.user != ticket.assigned_to and not request.user.is_staff:
        messages.error(request, '您没有权限进行维修')
        return redirect('tickets:ticket_detail', pk=pk)
    
    # 状态检查：只能在设备检测中状态下操作
    if ticket.status != 'testing':
        messages.error(request, '只能在设备检测中状态下操作')
        return redirect('tickets:ticket_detail', pk=pk)
    
    ticket.status = 'repairing'
    ticket.repairing_at = timezone.now()
    ticket.save()
    messages.success(request, '已开始维修，状态已更新为设备维修中')
    return redirect('tickets:ticket_detail', pk=pk)

@login_required
def ticket_quality_check(request, pk):
    """质量检查"""
    ticket = get_object_or_404(Ticket, pk=pk)
    # 权限检查：管理员或质检员可以进行质检
    if not (request.user.is_staff or 
            (hasattr(request.user, 'profile') and request.user.profile.role == 'quality_checker')):
        messages.error(request, '您没有权限进行质检')
        return redirect('tickets:ticket_detail', pk=pk)
    
    # 状态检查：只能在设备维修中状态下操作
    if ticket.status != 'repairing':
        messages.error(request, '只能在设备维修中状态下操作')
        return redirect('tickets:ticket_detail', pk=pk)
    
    ticket.status = 'quality_check'
    ticket.quality_check_at = timezone.now()
    ticket.quality_check_by = request.user
    ticket.save()
    messages.success(request, '质量检查完成，状态已更新为维修质检中')
    return redirect('tickets:ticket_detail', pk=pk)

@login_required
def ticket_list_quality_checker(request):
    """质检员查看所有工单"""
    if not (hasattr(request.user, 'profile') and request.user.profile.role == 'quality_checker'):
        messages.error(request, '您不是质检员，无法查看此页面')
        return redirect('dashboard')
    
    tickets = Ticket.objects.all().order_by('-created_at')
    return render(request, 'tickets/list_quality_checker.html', {'tickets': tickets})

@login_required
def ticket_complete(request, pk):
    """完成维修"""
    # 权限检查：只有管理员可以完成维修
    if not request.user.is_staff:
        messages.error(request, '您没有权限完成维修')
        return redirect('dashboard')
    
    ticket = get_object_or_404(Ticket, pk=pk)
    
    # 状态检查：只能在维修质检中状态下操作
    if ticket.status != 'quality_check':
        messages.error(request, '只能在维修质检中状态下操作')
        return redirect('tickets:ticket_detail', pk=pk)
    
    ticket.status = 'completed'
    ticket.completed_at = timezone.now()
    ticket.completed_by = request.user
    ticket.save()
    messages.success(request, '维修已完成，状态已更新为维修完成待返还')
    return redirect('tickets:ticket_detail', pk=pk)

@login_required
def ticket_return(request, pk):
    """设备返还"""
    # 权限检查：管理员或前台可以返还设备
    if not (request.user.is_staff or 
            (hasattr(request.user, 'profile') and request.user.profile.role == 'receptionist')):
        messages.error(request, '您没有权限返还设备')
        return redirect('dashboard')
    
    ticket = get_object_or_404(Ticket, pk=pk)
    
    # 状态检查：只能在维修完成待返还状态下返还设备
    if ticket.status != 'completed':
        messages.error(request, '只能在维修完成待返还状态下返还设备')
        return redirect('tickets:ticket_detail', pk=pk)
    
    ticket.status = 'returned'
    ticket.returned_at = timezone.now()
    ticket.returned_by = request.user
    ticket.save()
    
    # 将所有关联设备状态恢复为正常
    for asset in ticket.assets.all():
        asset.status = 'active'
        asset.save()
    
    messages.success(request, '设备已返还客户，所有关联设备状态已恢复为正常')
    return redirect('tickets:ticket_detail', pk=pk)
